<?php
/**
 * Created by PhpStorm.
 * User: qingyun
 * Date: 17/4/14
 * Time: 上午9:02
 */
namespace Admin\Controller;
use Common\Controller\AdminBaseController;

class AdminController extends AdminBaseController{
    public function index(){
        $manager = I('get.manager/s','');
        $page = I('get.page/d',1);
        $admin = M('Admin');
        //第二种分页
        $sql = empty($manager) ? '' : 'name like "%'.$manager.'%" or realName like "%'.$manager.'%"';
        $nums = 6;
        $counts = $admin->where($sql)->count();// 查询满足要求的总记录数
        $pagetotal = ceil($counts / $nums);//获取当前页第一个
        $current = empty($page) ? 0 : (($page - 1)*$nums);
        $list = $admin->where($sql)->order('id desc')->limit($current,$nums)->select();
        //第一种分页
        //$count = $admin->where($sql)->count();//获取到搜索时的总页数
        //$page = new \Think\Page($count,6,['manager' => $manager]);//实例化分页类 传入总记录数和每页显示的记录数，最后一个参数为搜索时的manager的值，tp会自动加载
        //$show = $page->show();//分页显示输出
        //$list = $admin->where($sql)->order('id desc')->limit($page->firstRow.','.$page->listRows)->select();
        //$this->assign('page',$show);//赋值分页输出

        $this->assign('manager',$manager);
        $this->assign('list',$list);// 赋值数据集
        $this->assign('pagetotal',$pagetotal);
        $this->display();
    }

    public function listPage(){
        sleep(1);
        $manager = I('get.manager/s','');
        $page = I('get.page/d',1);
        $admin = M('Admin');
        $sql = empty($manager) ? '' : 'name like "%'.$manager.'%" or realName like "%'.$manager.'%"';
        $nums = 6;
        $counts = $admin->where($sql)->count();
        $pagetotal = ceil($counts / $nums);
        $current = empty($page) ? 0 : (($page - 1)*$nums);
        $list = $admin->Alias('a')->field('a.id,a.name,a.img,a.status,a.realname,a.loginnum,a.logintime,g.title')->join('left join dx_admin_group ag on a.id = ag.uid left join dx_group g on ag.group_id = g.id')->where($sql)->order('id desc')->limit($current,$nums)->select();
        $listTr = '';
        foreach($list as $key => $val){
            $listTr .= '<tr><td>'.$val['id'].'</td><td>'.$val['name'].'</td><td>';
            if($val['img']){
                if(file_exists($val['img'])){
                    $listTr .= '<img src="'.'/'.$val['img'].'">';
                }else{
                    $listTr .= '<img src="/Upload/head/1492869608.jpg">';
                }
            }else{
                $listTr .= '<img src="/Upload/head/1492869608.jpg">';
            }
           $listTr .= '</td><td>'.$val['title'].'</td><td>'.$val['realname'].'</td><td>'.$val['loginnum'].'</td><td>'.$val['logintime'].'</td><td>';
            if($val['status']){
                $listTr .= '<a href="javascript:changeMode('.$val['id'].')" id="mode'.$val['id'].'" class="btn btn-outline btn-info">正常</a>';
            }else{
                $listTr .= '<a href="javascript:changeMode('.$val['id'].')" id="mode'.$val['id'].'" class="btn btn-warning btn-outline">禁用</a>';
            }
             $listTr .= '</td><td><a href="'.U('admin/edit?id='.$val['id']).'" type="button" class="btn btn-outline btn-info"><i class="fa fa-pencil-square-o"></i>修改 </a> <a href="javascript:changeDel('.$val['id'].')" class="btn btn-outline btn-danger"><i class="fa fa-trash-o"></i>删除</a></td></tr>';
        }
        $data = [
            'pages' => $pagetotal,
            'content' => $listTr
        ];
        exit(json_encode($data));
    }

    public function add(){//添加
        $option = M('group')->field('id,title')->where('status = 1')->select();//获取到下拉菜单的数据
        $this->assign('option',$option);
        $this->display();
    }

    public function edit(){
        if(IS_GET){
            $id = I("get.id/d",0);
            if(!$id){
                $this->error('非法操作');
            }
            $admininfo = M('admin')->alias('a')->field('a.id,a.name,a.img,a.realname,a.status,ag.group_id')->join('left join dx_admin_group ag on a.id = ag.uid')->where(['a.id' => $id])->find();
            $list = M('group')->field('id,title')->where('status = 1')->select();
            $this->assign('list',$list);
            $this->assign('admininfo',$admininfo);
            $this->display();
        }
    }
    /**
     * 保存管理员
     */
    public function save()
    {
        if (IS_POST || IS_AJAX) {
            $id = I('post.id/d', 0);
            if (!$id) {
                //获取账号
                $username = I('post.username/s', '');
                if (!$username) {
                    $this->ajaxReturn(['status' => 1, 'msg' => '账号不能为空']);
                }
                //获取角色
                $pid = I('post.pid/s', 0);
                //获取密码
                $pwd = I('post.password/s', '');
                if (!$pwd) {
                    $this->ajaxReturn(['status' => 1, 'msg' => '密码不能为空']);
                }
                //获取真实姓名
                $realname = I('post.realname/s', '');
                if (!$realname) {
                    $this->ajaxReturn(['status' => 1, 'msg' => '真实姓名不能为空']);
                }
                //获取状态
                $status = I('post.status/d');
                $litPath = '';
                if(!empty($_FILES)){
                    $litPath = uploadFile($_FILES['litpic']);
                }
                if(is_array($litPath)){
                    $this->ajaxReturn($litPath);
                }

                $admin = M('Admin');
                $admindata = $admin->where(['name' => $username])->find();//判断此条记录是否存在
                if ($admindata) {
                    $this->ajaxReturn(['status' => 1, 'msg' => '用户名已存在']);
                }

                //获取盐
                $salt = getRand();
                $data = [
                    'name' => $username,
                    'img' => $litPath,
                    'pwd' => md5($salt . $pwd),
                    'salt' => $salt,
                    'realName' => $realname,
                    'status' => $status
                ];


                //保存用户信息
                $admin->startTrans();//开启事务 两个表以上的关联才用
                $mid = $admin->add($data);//把$admin 改为 $this 会报一个很奇葩的错误，模板不存在   更新数据
                if (!$mid) {
                    $admin->rollback();//如果失败，执行事务回滚
                }
                //获取用户最后一次添加的id
                $mid = $admin->getLastInsID();
                $adminG = M('adminGroup');//数据库表名中间有下划线，可以把头字母大写,也可以原样写
                $is_ag = $adminG->add(['uid' => $mid, 'group_id' => $pid]);//为另一个关联的表添加数据
                if ($is_ag) {
                    $admin->commit();//提交事务
                } else {
                    $admin->rollback();//如果失败，执行事务回滚
                }
            } else {
                //获取分组
                $pid = I('post.pid/s', 0);
                //获取真实姓名
                $realname = I('post.realname/s', '');
                //获取状态
                $status = I('post.status/d');
                $admin = M('Admin');
                $adminid = $admin->where(['id' => $id])->find();//查询这条数据存在否
                if (empty($adminid)) {
                    $this->ajaxReturn(['status' => 1, 'msg' => '用户不存在']);//不存在 返回不存在
                }

                if(!empty($_FILES)){
                    $litPath = uploadFile($_FILES['litpic']);
                }

                if(is_array($litPath)){
                    $this->ajaxReturn($litPath);
                }


                if (empty($pid) && empty($realname) && empty($litPath)) {
                    $this->ajaxReturn(['status' => 0, 'msg' => '更新成功1']);//pid和realname都为空，则直接返回成功
                }

                if (!empty($pid) && empty($realname) && empty($litPath)) {
                    $isgroup = M('adminGroup')->add(['uid' => $id, 'group_id' => $pid], [], true);//pid有值，realname无值的情况下，只更新pid
                    if (!$isgroup) {
                        $this->ajaxReturn(['status' => 1, 'msg' => '更新失败1']);
                    }
                    $this->ajaxReturn(['status' => 0, 'msg' => '更新成功2']);
                }
                if (empty($pid) && (!empty($realname) || !empty($litPath))) {
                    $data = [];
                    if(!empty($realname)){
                        $data['realName'] = $realname;
                    }
                    if(!empty($litPath)){
                        $data['img'] = $litPath;
                    }
                    $real = $admin->where(['id' => $id])->setField($data);//pid无值，realname有值的情况下，只更新realname
                    if (!$real) {
                        $this->ajaxReturn(['status' => 1, 'msg' => '更新失败2']);
                    }
                    $this->ajaxReturn(['status' => 0, 'msg' => '更新成功3']);
                }
                $admin->startTrans();//开启事务 pid和realname都有值，就需要同时更新两个表的内容，这时就要开启事务
                $data = [];
                if(!empty($realname)){
                    $data['realName'] = $realname;
                }
                if(!empty($litPath)){
                    $data['img'] = $litPath;
                }
                $isreal = $admin->where('id=' . $id)->setField($data);//更新真实姓名
                if (!$isreal) {
                    $admin->rollback();//如果失败，执行事务回滚
                }
                $isgroup = M('adminGroup')->add(['uid' => $id, 'group_id' => $pid], [], true);//更新所属分组
                if (!$isgroup) {
                    $admin->rollback();//如果失败，执行事务回滚
                }
                $admin->commit();//提交事务
                $mid = true;
            }
            if ($mid === false) {
                $this->ajaxReturn(['status' => 1, 'msg' => '失败']);
            }
            $this->ajaxReturn(['status' => 0, 'msg' => '成功']);
        }
    }


    public function changeMode(){//更改状态
        if(IS_POST){
            $id = I('post.id/d',0);
            if(empty($id) || ($id == 1)){
                $this->ajaxReturn(['status' => 1,'msg' => '非法操作']);
            }
            $query = M('admin')->field('status')->where(['id' => $id])->find();
            if(empty($query['status'])){
                M('admin')->where(['id' => $id])->setField('status','1');
                $this->ajaxReturn(['status' => 0,'msg' => '已开启','data' => 1]);
            }else{
                M('admin')->where(['id' => $id])->setField('status','0');
                $this->ajaxReturn(['status' => 0,'msg' => '已关闭','data' => 0]);
            }
        }else{
            $this->ajaxReturn(['status' => 1,'msg' => '非法操作']);
        }
    }

    public function changeDel(){//删除
        if(IS_POST){
            $id = I('post.id/d',0);
            if(empty($id) || ($id == 1)){
                $this->ajaxReturn(['status' => 1,'msg' => '非法操作']);
            }
            $admin = M('admin');
            $admin->startTrans();
            $find = $admin->where(['id' => $id])->delete();
            if(!$find){
                $admin->rollback();
            }
            $ag = M('adminGroup');
            $real = $ag->where(['uid' => $id])->delete();
            if(!$real){
                $ag->rollback();
            }else{
                $ag->commit();
            }
            if(!$find){
                $this->ajaxReturn(['status' => 1,'msg' => '删除失败']);
            }else{
                $this->ajaxReturn(['status' => 0,'msg' => '删除成功']);
            }
        }else{
            $this->ajaxReturn(['status' => 1,'msg' => '非法操作']);
        }
    }

}